package org.example.client.controller;

import org.example.common.Response;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 客户端信息获取控制器
 */
@RestController
@RequestMapping("/api/client")
public class ClientController {

    @RequestMapping("/getClientIp")
    public Response<String> getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip != null && ip.length() > 0 && !"unknown".equalsIgnoreCase(ip)) {
            // X-Forwarded-For 可能包含多个 IP 地址，第一个为客户端真实 IP
            ip = ip.split(",")[0];
        } else {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();  // 如果无法获取，返回代理服务器的 IP
        }
        return Response.data(ip);
    }

}
